from django.http import HttpResponse
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
from libs.yuntongxun.sms import CCP

from libs.captcha.captcha import captcha
from verifications.constants import SMSIMAGE_EXPIRE_TIME


class RegisterImageCodeAPIView(APIView):
    def get(self,request,image_code_id):
        # 　2　生成图片验证码
        text,image = captcha.generate_captcha()
        #　3连接redis
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s'%image_code_id,SMSIMAGE_EXPIRE_TIME,text)
        return HttpResponse(image,content_type='image/jpeg')
# 发送短信
from verifications.serializers import RegisterSmsCodeSerializer
class RegisterSmsCodeAPIView(APIView):
    """
     GET   verifications/smscodes/(?P<mobile>1[3-9]\d{9})/?text=xxxx&image_code_id=xxx
    """
    def get(self,request,mobile):
        # 1.后端接收数据
        query_params = request.query_params

        # 2.校验数据 (数据格式,数据的内容[图片验证码是否正确])
        # text = query_params.get('text')
        # image_code_id=query_params.get('image_code_id')

        serializer = RegisterSmsCodeSerializer(data=query_params)
        serializer.is_valid(raise_exception=True)

        # 3.生成一个短信码
        import random
        sms_code = '%06d'%random.randint(0,999999)
        # 4.发送短信
        # CCP().send_template_sms(mobile,[sms_code,5],1)

        from celery_tasks.sms.tasks import send_sms_code
        #
        # # send_sms_code(mobile,sms_code)  错误的
        # # delay 的参数 同前边函数的参数
        send_sms_code.delay(mobile,sms_code)

        # 5.保存短信
        redis_conn = get_redis_connection('code')

        # redis_conn.setex(key,expire,value)
        redis_conn.setex('sms_%s'%mobile,5*60,sms_code)
        # 6.返回相应
        return Response({'msg':'ok'})




# Create your views here.
